import {Component, OnInit} from '@angular/core';
import {OrderService} from "../../services/order.service";
import {TipService} from "../../services/tip.service";
import {ExtendHttpService} from "../../../common/extend-http.service";
import {Router, ActivatedRoute} from "@angular/router";
import {IndexService} from "../../services/index.service";

@Component({
  selector: 'app-order-submit',
  templateUrl: './order-submit.component.html',
  styleUrls: ['./order-submit.component.css']
})
export class OrderSubmitComponent implements OnInit {

  is_open_called: any = ''; // 商户是否开启等叫服务 0开启等叫 1关闭等叫

  // 已选菜品列表
  selectFoodList = [];

  // tip提示类型
  tipType = 'error';

  // 总价
  countPrice = 0;

  // 总数量
  countNumber = 0;

  // 遮罩
  isLoading = false;

  // 桌号
  ofTid = '';
  ofPeopleNum = '';

  // 桌子类型
  tableState = '';

  // 加菜的信息
  addFoodInfo = {
    'of.order_content': '',
    'of.id': '',
    'tableClassName': '',
    'tableName': ''
  }

  orderRemark: any = ''; // 订单备注

  // 返回的页面 直接下单返回到桌子列表，加菜时返回到首页
  backUrl = '';

  // 提交按扭状态
  submitType = true;

  constructor(private orderService: OrderService,
              private tipService: TipService,
              private extendHttp: ExtendHttpService,
              private router: Router,
              private activatedRoute: ActivatedRoute,
              private indexService: IndexService) {
    this.activatedRoute.queryParams.subscribe(params => {
      this.ofTid = params['of.tid'];
      this.addFoodInfo['of.id'] = params['addOrderId'];
      this.tableState = params['tableState'];
    });
  }

  // 根据订单id获取餐桌名称
  getTableNames(orderId) {
    this.extendHttp.post('/merchantApp/singleprocess/getTableClass', {orderId: orderId}).subscribe(response => {
      let data = response.json();
      if (data.code == '0') {
        this.addFoodInfo.tableClassName = data.tableClassName;
        this.addFoodInfo.tableName = data.tableName;
      } else if (data.code == '-2001') {
        this.tipService.change(true, '登录超时，跳转到登录页面');
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 2000);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, data.message);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

  ngOnInit() {

    cBack = () => {
      $('#btn-back').trigger('click');
    }

    if (this.addFoodInfo['of.id']) {
      this.getTableNames(this.addFoodInfo['of.id']);
    }

    let tempArray = [], tempArray1 = [];

    tempArray = this.orderService.getSelectFoodList();
    tempArray.forEach((v) => {
      if (v.count > 0) {
        v.foodList.forEach(v1 => {
          let nprice = null;
          if (v1.is_discount === '1') nprice = v1.discount_price;
          if (v1.count > 0) {
            if (v1.type == '0') {
              tempArray1.push({
                id: v1.id,
                did: v1.did,
                type: 0,
                figure_url: v1.figure_url,
                name: v1.name,
                number: v1.count,
                is_called: v1.is_called,
                called_time: v1.called_time,
                price: nprice || v1.price,
                is_discount: v1.is_discount, // 是否优惠 0否 1是
                practice: ''
              });
            } else if (v1.type == '1') {
              v1.typeList.radioType.forEach(v2 => {
                tempArray1.push({
                  id: v1.id,
                  did: v1.did,
                  type: 1,
                  figure_url: v1.figure_url,
                  name: v1.name,
                  number: v2.count,
                  is_called: v1.is_called,
                  called_time: v1.called_time,
                  price: v2.price,
                  is_discount: v1.is_discount, // 是否优惠 0否 1是
                  practice: v2.value
                });
              });
            } else if (v1.type == '2') {
              v1.typeList.multiType.forEach(v2 => {
                tempArray1.push({
                  id: v1.id,
                  did: v1.did,
                  type: 2,
                  figure_url: v1.figure_url,
                  name: v1.name,
                  number: v2.count,
                  is_called: v1.is_called,
                  called_time: v1.called_time,
                  price: nprice || v1.price,
                  is_discount: v1.is_discount, // 是否优惠 0否 1是
                  practice: v2.value
                });
              });
            } else if (v1.type == '3') {
              v1.typeList.pumpType.forEach(v2 => {
                tempArray1.push({
                  id: v1.id,
                  did: v1.did,
                  type: 3,
                  figure_url: v1.figure_url,
                  name: v1.name,
                  number: v2.count,
                  is_called: v1.is_called,
                  called_time: v1.called_time,
                  price: nprice || v1.price,
                  is_discount: v1.is_discount, // 是否优惠 0否 1是
                  practice: v2.value
                });
              });
            }
          }
        });
      }
    });
    this.selectFoodList = tempArray1;

    // 总价， 总数量
    this.selectFoodList.forEach(v3 => {
      this.countPrice += v3.number * v3.price;
      this.countNumber += v3.number;
    });
  }

  // 获取商户信息-查看商户是否开启等叫服务
  getMerchantInfo() {
    this.extendHttp.post('/merchantApp/basics/loginInfo/getInfo', {}).subscribe(res => {
      if (res.json().code === '0') {
        this.is_open_called = res.json().merchant.is_open_called;
      }
    });
  }

  // 是否开启等叫
  isOpen1(v) {
    v.is_called = v.is_called === '0' ? '1' : '0';
  }

  submitData() {
    if (!this.isLoading) {
      if (this.selectFoodList.length) {
        if (!this.addFoodInfo['of.id']) {
          if (!this.ofPeopleNum) {
            this.tipType = 'error';
            this.tipService.change(true, '请输入用餐人数');
            return;
          }

          if (!/^[1-9]*[1-9][0-9]*$/.test(this.ofPeopleNum)) {
            this.tipType = 'error';
            this.tipService.change(true, '请输入正确的人数');
            return;
          }
        }

        let paramObj = null, url = '';
        paramObj = {
          'of.tid': this.ofTid,
          'of.people_num': this.ofPeopleNum,
          'of.order_content': JSON.stringify(this.selectFoodList),
          'of.remark': this.orderRemark,
        };
        url = '/merchantApp/singleprocess/oiginal';
        if (this.addFoodInfo['of.id']) {
          url = '/merchantApp/singleprocess/addDetail';
          paramObj = {'of.id': this.addFoodInfo['of.id'], 'of.order_content': JSON.stringify(this.selectFoodList)};
        }
        this.isLoading = !this.isLoading;
        this.extendHttp.post(url, paramObj).subscribe(response => {
          let data = response.json();
          if (data.code == '0') {
            this.indexService.clearData();
            this.submitType = false;
            this.isLoading = !this.isLoading;
            this.tipType = 'success';
            this.tipService.change(true, '订单提交成功');

            setTimeout(() => {
              this.router.navigate(['/main/table/table-list']);
            }, 1500);
          } else if (data.code == '-2001') {
            this.tipType = 'error';
            this.tipService.change(true, '登录超时，跳转到登录页面');
            setTimeout(() => {
              this.router.navigate(['/login']);
            }, 2000);
          } else {
            this.tipType = 'error';
            this.tipService.change(true, data.message);
            this.isLoading = !this.isLoading;
          }
        }, error => {
          this.tipType = 'error';
          this.tipService.change(true, '系统繁忙，操作失败！');
          this.isLoading = !this.isLoading;
        });
      } else {
        this.tipType = 'error';
        this.tipService.change(true, '请先选择菜品');
      }
    }
  }

}
